package com.by.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @version 1.0
 * @Author 彭彦彬
 * @Date 2025/4/2 14:14
 * @注释
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取授权
        String auth = request.getHeader("Authorization");
        if (null == auth) {
            //无权访问
            process(response, "无权访问！");
            return false;
        }
        String[] tmp = auth.split("\\s+");
        if (tmp.length != 2) {
            process(response, "认证信息错误！");
            return false;
        }

        //获取账号信息
        String info = tmp[1];
        String user = new String(Base64Utils.decode(info.getBytes()));
        //处理用户名和密码
        String[] gdt = user.split(":");
        if (!"admin".equals(gdt[0]) || !"123456".equals(gdt[1])) {
            process(response, "账号信息错误！");
            return false;
        }
        return true;
    }


    void process(HttpServletResponse response, String msg) {
        //设置内容编码
        response.setContentType("application/json;charset=utf-8");
        //获取响应输出流
        try {
            PrintWriter pw = response.getWriter();
            String info = "{\"code\":0,\"msg\":\"" + msg + "\"}";
            pw.write(info);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}